import { create } from 'zustand'
import { immer } from 'zustand/middleware/immer'
import type { AuthInfo, MemberProfile, UserInfo } from '@/store/types'
import { getStorageUserInfo, setStorageUserInfo } from '@/utils/ls/userInfo'
import { getLogout } from '@/apis/endpoint/home'
import { removeAuthInfo } from '@/utils/auth'
import { getMyGetuserinfo } from '@/apis/endpoint/my'

interface AuthStore extends AuthInfo {
  fetchMemberProfile(showLoading?: boolean): Promise<MemberProfile>
  setUserInfo(userInfo: UserInfo): void
  clearAuth(): void
  logout(): Promise<void>
  toggleAuthPannel(opened: boolean, fn?: IFn): void
}
export const useAuthStore = create<AuthStore>()(immer((set, get) => ({
  authPannel: { open: false, authFulfilledFn: null },
  userInfo: getStorageUserInfo() || null,
  memberProfile: null,
  fetchMemberProfile(showLoading?: boolean) {
    return getMyGetuserinfo()
    .send({showLoading})
    .then(profile => {
      set({ memberProfile: profile })
      return profile
    })
  },
  setUserInfo(userInfo) {
    set({userInfo})
    setStorageUserInfo(userInfo)
  },
  clearAuth: () => {
    const prevState = get().userInfo
    if (prevState) {
      const { miniVisitorId, nickName, openId, unionId } = prevState
      set({
        userInfo: {
          miniVisitorId,
          nickName,
          openId,
          unionId
        },
        memberProfile: null
      })
      removeAuthInfo()
    }
  },
  logout: () => {
    return getLogout().send().then(() => {
      get().clearAuth()
    })
  },
  toggleAuthPannel: (opened: boolean, fn?: IFn) => {
    set(state => {
      state.authPannel.open = opened
      state.authPannel.authFulfilledFn = typeof fn === "function" ? fn : null
    })
  }
})))
